<script setup>
import {useRoute, useRouter} from 'vue-router';
import {ref, onMounted} from 'vue';


const route = useRoute();
const router = useRouter();
const userId = route.params.userId;

import {useUserStore} from '@/stores/UserStores.js'
import {usePublicStore} from '@/stores/PublicStores.js'
import {ElMessage} from 'element-plus';
import {QuestionFilled, UploadFilled} from '@element-plus/icons-vue';

const UserStore = useUserStore()
const PublicStore = usePublicStore()
const {uploadTable} = UserStore
const {setKeys, updateKey} = PublicStore

onMounted(() => {
  // console.log('当前用户密钥为：', userId, '用于上传课程表');
});

const userName = ref('');
const fileList = ref([]);
// const imageViewer = ref(false);
const successImageViewer = ref(false)
const warningImageViewer = ref(false)

const loading = ref(false)


const beforeUpload = (e, files) => {
  fileList.value = files;
  const file = fileList.value[0];
  // 文件类型检查，这里允许常见的图片格式
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
  const isImageTypeAllowed = allowedTypes.includes(file.raw.type);

  // 文件大小检查
  const isLt2M = file.size / 1024 / 1024 < 2; // 限制文件大小不超过2MB

  if (!isImageTypeAllowed) {
    ElMessage.error('只能上传常见的图片格式文件（jpeg, jpg, png）!');
    fileList.value = [] // 清空文件列表，因为文件类型不符合
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!');
    fileList.value = [] // 清空文件列表，因为文件大小不符合
    return false
  }
  return true;
}

// 跳转到查看课程表页面
const viewTable = () => {
  // 跳转路由
  router.push({name: 'UpdateCourseSchedule'});
}

// 跳转到直接上传表格页面
const uploadTablePage = () => {
  // 跳转路由
  router.push({name: 'UploadTableSchedule', params: {userId}});
}

// 上传课程表
const submitFiles = () => {
  const file = fileList.value[0]?.raw;
  if (userId && userName.value && file) {
    loading.value = true
    uploadTable(userId, userName.value, file,
        () => {
          setKeys(userId)
          updateKey(userId)
          viewTable()
        },
        () => loading.value = false
    )
  } else {
    ElMessage.error('请输入正确的用户名和文件!');
  }
};

</script>

<template>
  <el-form>
    <el-form-item>
      <el-input type="text" v-model="userName" placeholder="请输入自己的真实姓名"/>
    </el-form-item>
    <el-form-item>
      <el-upload drag :auto-upload="false" :limit="1" v-model:file-list="fileList"
                 accept="image/jpeg,image/jpg,image/png"
                 @change="beforeUpload">
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">选择课程表文件</div>
        <el-tooltip placement="bottom" trigger="click">
          <template #content>
            <p>
              <el-link type="success" @click="successImageViewer = true" style="margin-right: 5px;">正确示例图片
              </el-link>
              <el-link type="warning" @click="warningImageViewer = true">错误示例图片</el-link>
            </p>
            <p>1.选择一个包含课程表的图片</p>

            <p>2. 上传的课程表图片尽量只包含一个表格，<br>这样图片识别的正确率最高。</p>
            <p>3. 如果想重新上传图片，请清除当前文件，再重新选择</p>
          </template>
          <el-button :icon="QuestionFilled" link @click.stop></el-button>
        </el-tooltip>
        <template #tip>
          <div class="el-upload__tip">
            图片大小不可超过2MB
          </div>
        </template>
      </el-upload>

    </el-form-item>

    <el-form-item>
      <el-button @click="submitFiles()" :loading="loading">上传课程表</el-button>
    </el-form-item>
    <el-form-item class="upload__table">
      <el-link type="danger" @click="uploadTablePage()">图片上传失败？点我试试</el-link>
    </el-form-item>
  </el-form>

  <el-image-viewer v-if="warningImageViewer" :url-list="['/public/warningExample.png']"
                   @close="warningImageViewer = false"></el-image-viewer>
  <el-image-viewer v-if="successImageViewer" :url-list="['/public/successExample.png']"
                   @close="successImageViewer = false"></el-image-viewer>

</template>
<style scoped>

.el-form {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.el-upload__text {
  width: 1000px;
  max-width: 80vw;
}

.upload__table {
  position: fixed;
  bottom: 50px;
}
</style>